<template>
  <div class="salary-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>薪资管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showCalculateDialog">
              <el-icon><Operation /></el-icon>
              薪资核算
            </el-button>
            <el-button type="success" @click="showBatchPayDialog">
              <el-icon><Money /></el-icon>
              批量发放
            </el-button>
            <el-button @click="handleExport">
              <el-icon><Download /></el-icon>
              导出薪资单
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable />
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="searchForm.department" placeholder="请选择部门" clearable>
            <el-option label="技术部" value="tech" />
            <el-option label="销售部" value="sales" />
            <el-option label="财务部" value="finance" />
          </el-select>
        </el-form-item>
        <el-form-item label="薪资月份">
          <el-date-picker
            v-model="searchForm.month"
            type="month"
            placeholder="选择月份"
            format="YYYY-MM"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item label="发放状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待发放" value="pending" />
            <el-option label="已发放" value="paid" />
            <el-option label="已作废" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 薪资列表 -->
      <el-table :data="tableData" border stripe v-loading="loading" show-summary :summary-method="getSummaries">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="month" label="薪资月份" width="120" />
        <el-table-column prop="employeeName" label="员工姓名" width="120" />
        <el-table-column prop="department" label="部门" width="120" />
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="baseSalary" label="基本工资" width="120">
          <template #default="{ row }">
            ¥{{ formatNumber(row.baseSalary) }}
          </template>
        </el-table-column>
        <el-table-column prop="performanceSalary" label="绩效工资" width="120">
          <template #default="{ row }">
            ¥{{ formatNumber(row.performanceSalary) }}
          </template>
        </el-table-column>
        <el-table-column prop="allowance" label="津贴补助" width="120">
          <template #default="{ row }">
            ¥{{ formatNumber(row.allowance) }}
          </template>
        </el-table-column>
        <el-table-column prop="overtimePay" label="加班费" width="100">
          <template #default="{ row }">
            ¥{{ formatNumber(row.overtimePay) }}
          </template>
        </el-table-column>
        <el-table-column prop="deduction" label="扣款" width="100">
          <template #default="{ row }">
            <span class="deduction-amount">-¥{{ formatNumber(row.deduction) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalSalary" label="应发工资" width="120">
          <template #default="{ row }">
            <span class="total-amount">¥{{ formatNumber(row.totalSalary) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="actualSalary" label="实发工资" width="120">
          <template #default="{ row }">
            <span class="actual-amount">¥{{ formatNumber(row.actualSalary) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">详情</el-button>
            <el-button v-if="row.status === 'pending'" type="success" size="small" @click="handlePay(row)">发放</el-button>
            <el-button type="info" size="small" @click="handlePrint(row)">打印</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 薪资核算对话框 -->
    <el-dialog v-model="calculateDialogVisible" title="薪资核算" width="800px">
      <el-form :model="calculateForm" label-width="120px">
        <el-form-item label="核算月份">
          <el-date-picker
            v-model="calculateForm.month"
            type="month"
            placeholder="选择月份"
            format="YYYY-MM"
            value-format="YYYY-MM"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="核算范围">
          <el-radio-group v-model="calculateForm.scope">
            <el-radio label="all">全体员工</el-radio>
            <el-radio label="department">按部门</el-radio>
            <el-radio label="employee">指定员工</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="calculateForm.scope === 'department'" label="选择部门">
          <el-select v-model="calculateForm.department" placeholder="请选择部门" style="width: 100%">
            <el-option label="技术部" value="tech" />
            <el-option label="销售部" value="sales" />
            <el-option label="财务部" value="finance" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="calculateForm.scope === 'employee'" label="选择员工">
          <el-select v-model="calculateForm.employees" multiple placeholder="请选择员工" style="width: 100%">
            <el-option label="张三" value="zhangsan" />
            <el-option label="李四" value="lisi" />
          </el-select>
        </el-form-item>
        <el-form-item label="核算项目">
          <el-checkbox-group v-model="calculateForm.items">
            <el-checkbox label="baseSalary">基本工资</el-checkbox>
            <el-checkbox label="performance">绩效工资</el-checkbox>
            <el-checkbox label="allowance">津贴补助</el-checkbox>
            <el-checkbox label="overtime">加班费</el-checkbox>
            <el-checkbox label="deduction">扣款</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="calculateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCalculate" :loading="calculateLoading">开始核算</el-button>
      </template>
    </el-dialog>

    <!-- 薪资详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="薪资详情" width="800px">
      <div class="salary-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="薪资月份">{{ viewData.month }}</el-descriptions-item>
          <el-descriptions-item label="员工姓名">{{ viewData.employeeName }}</el-descriptions-item>
          <el-descriptions-item label="部门">{{ viewData.department }}</el-descriptions-item>
          <el-descriptions-item label="职位">{{ viewData.position }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">收入明细</el-divider>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="基本工资">¥{{ formatNumber(viewData.baseSalary) }}</el-descriptions-item>
          <el-descriptions-item label="绩效工资">¥{{ formatNumber(viewData.performanceSalary) }}</el-descriptions-item>
          <el-descriptions-item label="津贴补助">¥{{ formatNumber(viewData.allowance) }}</el-descriptions-item>
          <el-descriptions-item label="加班费">¥{{ formatNumber(viewData.overtimePay) }}</el-descriptions-item>
          <el-descriptions-item label="其他收入">¥{{ formatNumber(viewData.otherIncome || 0) }}</el-descriptions-item>
          <el-descriptions-item label="应发工资" class="highlight">
            ¥{{ formatNumber(viewData.totalSalary) }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">扣款明细</el-divider>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="个人所得税">¥{{ formatNumber(viewData.tax || 0) }}</el-descriptions-item>
          <el-descriptions-item label="社保">¥{{ formatNumber(viewData.socialSecurity || 0) }}</el-descriptions-item>
          <el-descriptions-item label="公积金">¥{{ formatNumber(viewData.housingFund || 0) }}</el-descriptions-item>
          <el-descriptions-item label="迟到扣款">¥{{ formatNumber(viewData.lateDeduction || 0) }}</el-descriptions-item>
          <el-descriptions-item label="其他扣款">¥{{ formatNumber(viewData.otherDeduction || 0) }}</el-descriptions-item>
          <el-descriptions-item label="扣款合计" class="highlight">
            ¥{{ formatNumber(viewData.deduction) }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">最终薪资</el-divider>
        <div class="final-salary">
          <div class="label">实发工资：</div>
          <div class="amount">¥{{ formatNumber(viewData.actualSalary) }}</div>
        </div>
      </div>
    </el-dialog>

    <!-- 批量发放对话框 -->
    <el-dialog v-model="batchPayDialogVisible" title="批量发放薪资" width="600px">
      <el-alert
        title="温馨提示"
        type="warning"
        description="批量发放将对所有选中的待发放薪资进行发放操作，请确认后操作。"
        :closable="false"
        show-icon
        style="margin-bottom: 20px"
      />
      <el-form :model="batchPayForm" label-width="100px">
        <el-form-item label="发放月份">
          <el-date-picker
            v-model="batchPayForm.month"
            type="month"
            placeholder="选择月份"
            format="YYYY-MM"
            value-format="YYYY-MM"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="发放人数">
          <el-input v-model="batchPayForm.count" readonly />
        </el-form-item>
        <el-form-item label="发放总额">
          <el-input v-model="batchPayForm.totalAmount" readonly>
            <template #prepend>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="支付密码">
          <el-input v-model="batchPayForm.password" type="password" placeholder="请输入支付密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchPayDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchPay" :loading="payLoading">确认发放</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Operation, Money, Download, View, Edit, Delete, Search, Refresh } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const calculateDialogVisible = ref(false)
const viewDialogVisible = ref(false)
const batchPayDialogVisible = ref(false)
const calculateLoading = ref(false)
const payLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  department: '',
  month: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 100
})

// 核算表单
const calculateForm = reactive({
  month: '',
  scope: 'all',
  department: '',
  employees: [],
  items: ['baseSalary', 'performance', 'allowance', 'overtime', 'deduction']
})

// 批量发放表单
const batchPayForm = reactive({
  month: '',
  count: '0',
  totalAmount: '0',
  password: ''
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    month: '2024-01',
    employeeName: '张三',
    department: '技术部',
    position: '技术总监',
    baseSalary: 20000,
    performanceSalary: 5000,
    allowance: 2000,
    overtimePay: 1000,
    deduction: 3500,
    totalSalary: 28000,
    actualSalary: 24500,
    status: 'paid',
    tax: 2000,
    socialSecurity: 1000,
    housingFund: 500,
    lateDeduction: 0,
    otherDeduction: 0,
    otherIncome: 0
  },
  {
    id: 2,
    month: '2024-01',
    employeeName: '李四',
    department: '销售部',
    position: '销售经理',
    baseSalary: 15000,
    performanceSalary: 3000,
    allowance: 1500,
    overtimePay: 500,
    deduction: 2500,
    totalSalary: 20000,
    actualSalary: 17500,
    status: 'pending',
    tax: 1500,
    socialSecurity: 800,
    housingFund: 200,
    lateDeduction: 0,
    otherDeduction: 0,
    otherIncome: 0
  }
])

const viewData = ref({})

// 方法
const formatNumber = (value) => {
  if (typeof value === 'number') {
    return value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
  }
  return '0.00'
}

const getStatusType = (status) => {
  const map = {
    'pending': 'warning',
    'paid': 'success',
    'cancelled': 'info'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    'pending': '待发放',
    'paid': '已发放',
    'cancelled': '已作废'
  }
  return map[status] || status
}

const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    
    const values = data.map(item => Number(item[column.property]))
    if (column.property === 'baseSalary' || column.property === 'performanceSalary' || 
        column.property === 'allowance' || column.property === 'overtimePay' || 
        column.property === 'deduction' || column.property === 'totalSalary' || 
        column.property === 'actualSalary') {
      sums[index] = '¥' + values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    } else {
      sums[index] = ''
    }
  })
  return sums
}

const handleSearch = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('查询成功')
  }, 1000)
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    department: '',
    month: '',
    status: ''
  })
}

const showCalculateDialog = () => {
  calculateDialogVisible.value = true
}

const showBatchPayDialog = () => {
  batchPayForm.month = ''
  batchPayForm.count = '2'
  batchPayForm.totalAmount = '42000.00'
  batchPayForm.password = ''
  batchPayDialogVisible.value = true
}

const confirmCalculate = () => {
  calculateLoading.value = true
  
  setTimeout(() => {
    calculateLoading.value = false
    calculateDialogVisible.value = false
    ElMessage.success('薪资核算完成')
  }, 2000)
}

const handleView = (row) => {
  viewData.value = row
  viewDialogVisible.value = true
}

const handlePay = (row) => {
  ElMessageBox.confirm('确定要发放该员工的薪资吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('薪资发放成功')
  })
}

const handlePrint = (row) => {
  ElMessage.info('打印薪资单')
}

const confirmBatchPay = () => {
  if (!batchPayForm.password) {
    ElMessage.warning('请输入支付密码')
    return
  }
  
  payLoading.value = true
  
  setTimeout(() => {
    payLoading.value = false
    batchPayDialogVisible.value = false
    ElMessage.success('批量发放成功')
  }, 2000)
}

const handleExport = () => {
  ElMessage.success('导出成功')
}

const handleSizeChange = (size) => {
  pagination.size = size
}

const handleCurrentChange = (page) => {
  pagination.page = page
}
</script>

<style scoped>
.salary-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-form {
  margin-bottom: 20px;
}

.deduction-amount {
  color: #f56c6c;
  font-weight: 500;
}

.total-amount {
  color: #409eff;
  font-weight: 600;
}

.actual-amount {
  color: #67c23a;
  font-weight: 600;
  font-size: 16px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.salary-detail {
  padding: 10px 0;
}

.salary-detail :deep(.highlight .el-descriptions__cell) {
  background: #f5f7fa;
  font-weight: 600;
}

.final-salary {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 30px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  margin-top: 20px;
}

.final-salary .label {
  font-size: 20px;
  color: white;
  font-weight: 500;
}

.final-salary .amount {
  font-size: 36px;
  color: white;
  font-weight: 600;
}
</style>
